package gui.newgui.mainwindow;

import gui.newgui.newtournamentwindow.NewTournamentWindow2;

import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.xml.sax.SAXException;

import tournamentData.TournamentData;
import core.Constants;
import core.GuiComponentLabels;
import core.XMLWriter;

public class MenuBarController {
	private final MainWindow window;

	public MenuBarController(MainWindow mainWindow) {
		this.window = mainWindow;
	}

	public void doCreateNewTournament() {
		// TODO wird noch exception
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				NewTournamentWindow2 inst = new NewTournamentWindow2(MenuBarController.this.window);
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}

	public void closeWindow() {
		this.window.dispose();
	}

	public void doSave() {
		try {
			File toWrite = TournamentData.getInstance().getOpenedFile();
			if (toWrite == null) {
				toWrite = new File(XMLWriter.getFileName(TournamentData.getInstance().getGeneralTournamentInformation().getTournamentName(), TournamentData.getInstance()
						.getGeneralTournamentInformation().getStartDate()));
			}
			XMLWriter.writeToFile(toWrite);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doOpen() {
		boolean isChosen = false;

		final JFileChooser chooser = new JFileChooser();
		final FileFilter filter = new FileNameExtensionFilter("xml Dateien", Constants.XML_FILEENDING);
		chooser.addChoosableFileFilter(filter);
		final int ret = chooser.showDialog(null, GuiComponentLabels.OPEN);

		if (ret == JFileChooser.APPROVE_OPTION) {
			final File fileToOpen = chooser.getSelectedFile();

			/** open the main Window */
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					MainWindow inst;
					inst = new MainWindow(fileToOpen);
					inst.setLocationRelativeTo(null);
					inst.setVisible(true);
				}
			});
			isChosen = true;
		}

		if (isChosen) {
			this.window.dispose();
		}
	}
}
